package com.trinity.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.trinity.common.core.controller.BaseController;
import com.trinity.common.core.domain.AjaxResult;
import com.trinity.common.utils.StringUtils;
import com.trinity.service.IWxUserService;
import com.trinity.utils.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wx/user/")
public class WxMaUserControllerV2 extends BaseController {

    private final WxMaService wxMaService;
    @Resource
    private IWxUserService wxUserService;

    /**
     * 登陆接口
     */
    @GetMapping("/login")
    public AjaxResult login(String code, String phone) {
        if (StringUtils.isBlank(code)) {
            return error("empty jscode");
        }
        String appid = wxMaService.getWxMaConfig().getAppid();
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        try {
            return wxUserService.wxLongByAppidAndCode(appid, code, phone);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping(value = "/phone", method = RequestMethod.GET)
    public String wechatSession(@RequestParam String code) throws WxErrorException {
        if (StringUtils.isBlank(code)) {
            return "empty jscode";
        }
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(code);
        return JsonUtils.toJson(phoneNoInfo);
    }


}
